﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using teacher.Util;
using teacher.DAL;

namespace tearcher.Controllers
{
    public class UploadController : Controller
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="UserInfo">用户信息.l,kjm,.lkmn,</param>
        /// <param name="directory">目录</param>
        /// <param name="file">文件</param>
        /// <returns></returns>
        public string UploadFile(string fileName, string width, string height, string flag, string type)
        {
            try
            {
                string file_url = "";
                HttpPostedFileBase file1 = Request.Files.Count > 0 ? Request.Files[0] : null;
                if (file1 != null)
                {
                    //取得文件的扩展名,并转换成小写
                    string fileExtension = System.IO.Path.GetExtension(file1.FileName).ToLower();
                    //限定只能上传jpg和gif图片
                    string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
                    //对上传的文件的类型进行一个个匹对
                    //验证文件格式
                    if (allowExtension.Contains(fileExtension))
                    {
                        if (file1.ContentLength < 1024 * 1024 * 10)
                        {
                            string dir = Request.MapPath(String.Format("~{0}/", "/upload/teacher/"));
                            if (!System.IO.Directory.Exists(dir))
                            {
                                System.IO.Directory.CreateDirectory(dir);
                            }
                            file1.SaveAs(Path.Combine(dir + fileName));

                            System.Drawing.Image iSource = System.Drawing.Image.FromFile(Path.Combine(dir + fileName));
                            if (iSource.Width > 1024 && iSource.Height > 1024 && "0".Equals(type))
                            {
                                int h = Convert.ToInt32(1024 * iSource.Height / iSource.Width);
                                iSource.Dispose();
                                Helper.SizeImage(Path.Combine(dir + fileName), Path.Combine(dir + "small_t" + fileName), Convert.ToInt32(height), Convert.ToInt32(width));
                                bool rs = Helper.CompressImage(Path.Combine(dir + fileName), Path.Combine(dir + "t" + fileName), h, 1024, 50);
                                if (rs)
                                {
                                    try
                                    {
                                        System.IO.File.Delete(Path.Combine(dir + fileName));
                                    }
                                    catch
                                    {
                                        Helper.WriteLog("删除原图失败");
                                    }
                                }
                                fileName = "t" + fileName;
                            }
                            else
                            {
                                Helper.SizeImage(Path.Combine(dir + fileName), Path.Combine(dir + "small_" + fileName), Convert.ToInt32(height), Convert.ToInt32(width));
                            }
                        }
                        else
                        {
                            Helper.WriteLog("上传文件必须小于10MB");
                            return Helper.sendErrorJson(Request, "上传文件必须小于10MB");

                        }
                    }
                    else
                    {
                        Helper.WriteLog("上传的文件格式不正确，请上传.jpg|.png|.gif|.bmp文件格式");
                        return Helper.sendErrorJson(Request, "上传的文件格式不正确，请上传.jpg|.png|.gif|.bmp文件格式");
                    }
                }
                else
                {
                    Helper.WriteLog("未选择文件");
                    return Helper.sendErrorJson(Request, "未选择文件");
                }
                return Helper.sendOKJson(Request, new { url = "/upload/teacher/" + fileName });
            }
            catch (Exception e)
            {
                return Helper.sendErrorJson(Request, "上传文件异常");
                Helper.WriteLog("上传文件异常:\n" + e.Message);
            }

        }


        //上传成长档案短视频
        public string UploadGrowVideo()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;               
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "upload\\teacher\\video";//服务器保存路径
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名

                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + fileNameHouZui;
                file.SaveAs(fileName);

                //组装返回数据
                string fileNameSave = "/upload/teacher/video/" + time + fileNameHouZui;//保存到数据库的视频路径
                var fileJson = "{\"state\":\"success\",\"videoURL\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "Upload/UploadGrowVideo，" + ex.Message;
                LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        /// <summary>
        /// 上传短视频图片
        /// </summary>
        /// <returns></returns>
        public string UploadVideoImg()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "upload\\teacher\\videoImg";
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名
                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + "_T" + fileNameHouZui;
                file.SaveAs(fileName);
                string newFilePath = savePath + "\\" + time + fileNameHouZui;
                ImgChuLi.SendSmallImage(fileName, newFilePath, 200, 200, 80, "CUT");//对头像进行裁剪
                //删除上传的原始图片
                System.IO.File.Delete(fileName);
                //组装返回数据
                string fileNameSave = "/upload/teacher/videoImg/" + time + fileNameHouZui;//保存到数据库的图片路径
                var fileJson = "{\"state\":\"success\",\"filePath\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "Upload/UploadVideoImg，" + ex.Message;
                LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        //保存视频数据到数据库
        public string SaveGrowVideo(string userId, string word, string schoolId, string classId, string videoURL, string videoImgURL)
        {
            string backmsg = "";
            try
            {
                int count = new GrowDAL().AddGrowVideo(userId, word, schoolId, classId, videoURL, videoImgURL);
                backmsg = count.ToString();
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/SaveGrowVideo，" + ex.Message;
                LogManager.AddLog(msg, saveFolder);
                backmsg = "error500";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backmsg + ")";
            return back;
        }

    }
}
